package com.jukte.recipe.adapters;

import java.util.List;

import com.ewhat.recipes.R;
import com.jukte.recipe.models.Ingredient;
import com.jukte.recipe.utils.SpecialCheckBox;
import com.jukte.recipe.utils.SpecialCheckBox.OnClickListener;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

public class AddtoCartAdapter extends ArrayAdapter<Ingredient>{

	 private final List<Ingredient> list;
	  private final Activity context;

	  public AddtoCartAdapter(Activity context, List<Ingredient> list) {
	    super(context, R.layout.row_add_to_cart, list);
	    this.context = context;
	    this.list = list;
	  }

	  static class ViewHolder {
	    protected TextView text;
	    protected SpecialCheckBox checkbox;
	  }

	  
	  public List<Ingredient> getItems()
	  {
		  return list;
	  }
	  
	  private boolean getBooleanFromInt(int i)
	  {
		 return i==1?true:false;
	  }
	  private int getIntToBoolean(boolean flag)
	  {
		 return flag==true?1:0;
	  }
	  @Override
	  public View getView(int position, View convertView, ViewGroup parent) {
	    View view = null;
	    if (convertView == null) {
	      LayoutInflater inflator = context.getLayoutInflater();
	      view = inflator.inflate(R.layout.row_add_to_cart, null);
	      final ViewHolder viewHolder = new ViewHolder();
	      viewHolder.text = (TextView) view.findViewById(R.id.label);
	      viewHolder.checkbox = (SpecialCheckBox) view.findViewById(R.id.check);
	      viewHolder.checkbox.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					Ingredient element = (Ingredient) viewHolder.checkbox.getTag();
			         element.setIsAddedToCart(getIntToBoolean(viewHolder.checkbox.isChecked()));
				}
			});
	 
	      view.setTag(viewHolder);
	      viewHolder.checkbox.setTag(list.get(position));
	    } else {
	      view = convertView;
	      ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
	    }
	    ViewHolder holder = (ViewHolder) view.getTag();
	    holder.text.setText(list.get(position).getText());
	    holder.checkbox.setChecked(getBooleanFromInt(list.get(position).getIsAddedToCart()));
	    return view;
	  }
	} 
	
	

	


